<template>
  <div class="page-container">
    <!-- <van-nav-bar title="我的订单" left-text="" right-text="" /> -->
    <div v-if="showLoading" class="loading-wrapper">
      <van-loading type="spinner">支付中...</van-loading>
    </div>
    <van-image
      width="100%"
      height="225"
      :src="require('@/assets/package_header.jpg')"
    />
    <div class="goods-list__title">我的订单</div>
    <div class="goods-list__tips">
      先预约姓名相同最早的订单；我的预约信息要确认才能预约姓名相同的下次
    </div>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        :finished-text="list.length === 0 ? '暂无数据' : '没有更多了'"
        @load="onLoad"
      >
        <van-cell v-for="item in list" :key="item.id" class="list-cell">
          <div slot="default">
            <div class="goods-container">
              <van-image
                width="80px"
                height="80px"
                :src="item.product.image"
                class="van-col imageBorder"
              />
              <van-row class="content-box">
                <div class="content-name">{{ item.product.store_name }}</div>
                <div class="content-des">
                  姓名: {{ item.order_name }}
                  {{
                    `  共${item.total_appointment_num}次剩${item.appointment_num}次`
                  }}
                </div>
                <div v-if="item.paid === 1" class="content-des">
                  支付: {{ item.pay_time }}
                </div>
                <van-tag
                  v-if="item.status === 3"
                  round
                  type="warning"
                  size="large"
                  color="gray"
                  class="bottom_right_icon"
                >已取消</van-tag>
                <van-tag
                  v-if="item.status !== 3 && item.paid === 1"
                  round
                  type="primary"
                  size="large"
                  class="top_right_icon"
                  @click="goCourseRecord(item)"
                >疗程记录</van-tag>
                <van-tag
                  v-if="
                    item.status !== 3 &&
                      item.paid === 1 &&
                      item.can_appointment &&
                      item.appointment_num > 0
                  "
                  round
                  type="primary"
                  size="large"
                  class="bottom_right_icon"
                  @click="goDetail(item)"
                >预约</van-tag>
                <van-tag
                  v-if="item.status !== 3 && item.paid === 0"
                  round
                  type="primary"
                  size="large"
                  class="bottom_right_icon"
                  @click="goPayment(item)"
                >支付</van-tag>
                <van-tag
                  v-if="item.status !== 3 && item.paid === 0"
                  round
                  type="warning"
                  size="large"
                  class="bottom_right_icon2"
                  @click="cancelOrder(item)"
                >取消</van-tag>
              </van-row>
            </div>
          </div>
        </van-cell>
      </van-list>
    </van-pull-refresh>
    <van-tabbar
      v-model="tabbarActive"
      class="page-tottom-tabbar"
      @change="changeTabbar"
    >
      <van-tabbar-item name="home" icon="home-o">首页</van-tabbar-item>
      <van-tabbar-item name="case" icon="star-o">数据</van-tabbar-item>
      <van-tabbar-item name="package" icon="bag-o">订单</van-tabbar-item>
      <van-tabbar-item name="personal" icon="friends-o">我的</van-tabbar-item>
    </van-tabbar>

    <!-- 支付弹框 -->
    <van-dialog
      v-model="payDialogVisible"
      title=""
      :show-cancel-button="false"
      :show-confirm-button="false"
      close-on-click-overlay
    >
      <div class="pay-container">
        <van-icon
          name="cross"
          class="pay-dialong-icon-close"
          @click="payDialogVisible = false"
        />
        <div class="pay-dialog-price">
          ￥{{ Number(orderInfo.product.price) }}
        </div>
        <van-radio-group v-model="payRadio">
          <van-cell clickable @click="payRadio = 1">
            <template #title>
              <i class="iconfont icon-adl-weixin" />
              <div>微信支付</div>
            </template>
            <template #right-icon>
              <van-radio :name="1" />
            </template>
          </van-cell>
          <!-- <van-cell clickable @click="payRadio = 2">
            <template #title>
              <i class="iconfont icon-adl-zhifubao" />
              <div>支付宝支付</div>
            </template>
            <template #right-icon>
              <van-radio :name="2" />
            </template>
          </van-cell> -->
        </van-radio-group>
        <div class="pay-dialog-button-box">
          <van-button
            type="info"
            round
            class="pay-dialog-button"
            @click="jumpPayment"
          >去支付</van-button>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { urlScheme } from '@/api/user'
import { list, pay, detail, cancel } from '@/api/order'
import {
  Button,
  Tabbar,
  TabbarItem,
  Swipe,
  SwipeItem,
  List,
  PullRefresh,
  Card,
  Tag,
  Icon,
  RadioGroup,
  Radio,
  // eslint-disable-next-line no-unused-vars
  Toast,
  Dialog
} from 'vant'

let isPayTimer = null

export default {
  name: 'Home',
  components: {
    [Button.name]: Button,
    [Tabbar.name]: Tabbar,
    [TabbarItem.name]: TabbarItem,
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    [List.name]: List,
    [PullRefresh.name]: PullRefresh,
    [Card.name]: Card,
    [Tag.name]: Tag,
    [Icon.name]: Icon,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio
  },
  data() {
    return {
      tabbarActive: 'package',
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      filterData: {
        limit: 10,
        page: 0
      },
      payDialogVisible: false, // 支付方式弹窗
      payRadio: 1,
      orderInfo: {
        // 订单信息，支付弹窗用
        product: {
          price: null
        }
      },
      showLoading: false // 支付loading
    }
  },
  created() {
    const status = window.localStorage.getItem('isPaying')
    if (+status === 1) {
      this.showLoading = true
      clearTimeout(isPayTimer)
      this.loopPayStatus(4)
    }
  },
  methods: {
    // 列表
    getList(refresh) {
      const _self = this
      list(this.filterData).then((res) => {
        if (res.error.code === 0) {
          // 加载状态结束
          _self.loading = false
          // 数据全部加载完成
          if (refresh === 'refresh') {
            this.list = res.data.list
          } else {
            const tempList = [...this.list, ...res.data.list]
            this.list = tempList
          }
          if (this.list.length >= res.data.totalCount) {
            _self.finished = true
          } else {
            _self.finished = false
          }
        }
      })
    },
    onLoad() {
      this.filterData.page += 1
      this.getList()
    },
    onRefresh() {
      this.refreshing = false
      this.finished = true // 防止下拉刷新发送了两次请求的问题
      this.filterData.page = 1
      this.getList('refresh')
      this.list = []
    },
    // 切换菜单
    changeTabbar(e) {
      if (e === 'home') {
        this.$router.push({ name: 'home' })
      } else if (e === 'case') {
        this.$router.push({ name: 'case' })
      } else if (e === 'package') {
        this.$router.push({ name: 'package' })
      } else if (e === 'personal') {
        this.$router.push({ name: 'personal' })
      }
    },
    // 预约
    goDetail(item) {
      this.$router.push({
        name: 'packageDetails',
        query: {
          id: item.order_id
        }
      })
    },
    // 支付
    goPayment(item) {
      this.orderInfo = item
      this.payDialogVisible = true
    },
    // 疗程记录
    goCourseRecord(item) {
      this.$router.push({
        name: 'courseRecord',
        query: {
          id: item.order_id
        }
      })
    },
    // 取消订单
    cancelOrder(item) {
      Dialog.confirm({
        title: '',
        message: '是否取消订单？',
        showCancelButton: true
      })
        .then(() => {
          cancel({ order_id: item.order_id }).then((res) => {
            if (res.error.code === 0 && res.data) {
              this.onRefresh()
            }
          })
        })
        .catch(() => {})
    },
    // 跳转逻辑
    jumpPayment() {
      // if (this.payRadio === 1) {
      //   urlScheme({
      //     order_id: this.orderInfo.order_id
      //   }).then((res) => {
      //     //
      //   })
      //   Toast('功能开发中')
      //   return
      // }
      this.payDialogVisible = false
      this.showLoading = true
      if (this.payRadio === 1) {
        urlScheme({
          order_id: this.orderInfo.order_id
        }).then((res) => {
          window.localStorage.setItem('orderId', this.orderInfo.order_id)
          window.localStorage.setItem('isPaying', '1')
          location.href = res.data
          clearTimeout(isPayTimer)
          this.loopPayStatus(5)
        })
      } else if (this.payRadio === 2) {
        const params = {
          order_id: this.orderInfo.order_id,
          pay_channel: this.payRadio
        }
        pay(params).then((res) => {
          if (res.error.code === 0) {
            window.localStorage.setItem('orderId', this.orderInfo.order_id)
            window.localStorage.setItem('isPaying', '1')
            clearTimeout(isPayTimer)
            this.loopPayStatus(2)
            // ios里好像不支持window.open打开，所以就改成了a标签模拟点击跳转
            const link = document.createElement('a')
            link.setAttribute(
              'href',
              window.location.origin +
                '/middle.html?jump=' +
                encodeURIComponent(res.data.expend.pay_info)
            )
            document.body.appendChild(link)
            link.click()
          }
        })
      }
    },
    async loopPayStatus(times) {
      if (times === 0) {
        this.showLoading = false
        window.localStorage.removeItem('isPaying')
        window.localStorage.removeItem('orderId')
        Dialog.confirm({
          title: '',
          message: '支付异常！请检查支付是否成功，成功可以预约，失败则需重新支付！',
          showCancelButton: false
        }).then(() => {
          // window.location.reload()
        })
        return Promise.reject()
      }
      try {
        const order_id = window.localStorage.getItem('orderId')
        const res = await detail({
          order_id: order_id
        })
        const {
          order: { paid }
        } = res.data
        const { code } = res.error
        if (code !== 0) {
          // window.location.reload()
          window.localStorage.removeItem('isPaying')
          window.localStorage.removeItem('orderId')
        }
        if (paid === 0) {
          const self = this
          isPayTimer = setTimeout(() => {
            self.loopPayStatus(times - 1)
          }, 5000)
        } else if (paid === 1) {
          this.showLoading = false
          Dialog.confirm({
            title: '',
            message: '支付成功',
            showCancelButton: false
          }).then(() => {
            window.location.reload()
            window.localStorage.removeItem('isPaying')
            window.localStorage.removeItem('orderId')
          })
        } else {
          Dialog.confirm({
            title: '',
            message: '未能获取支付状态，请刷新页面',
            showCancelButton: false
          }).then(() => {
            // window.location.reload()
            window.localStorage.removeItem('isPaying')
            window.localStorage.removeItem('orderId')
          })
        }
      } catch (err) {
        console.log(err)
        // window.location.reload()
        // window.localStorage.removeItem('isPaying')
        // window.localStorage.removeItem('orderId')
        const self = this
        isPayTimer = setTimeout(() => {
          self.loopPayStatus(times - 1)
        }, 5000)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.loading-wrapper {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;

  display: flex;
  flex-flow: column nowrap;
  align-items: center;
  justify-content: center;
}
.van-pull-refresh {
  .van-list {
    min-height: calc(100vh - 331px);
  }
}
.page-container {
  padding-bottom: 50px;
  box-sizing: border-box;
  overflow: auto;
}
.goods-list__title {
  color: #323233;
  font-weight: 500;
  font-size: 16px;
  text-align: center;
}
.goods-list__tips {
  padding: 0 0 5px 5px;
}
.goods-container {
  padding: 5px;
  position: relative;
}
.content-box {
  background-color: #fff;
}
.list-cell {
  margin-bottom: 10px;
  border-radius: 3px;
  padding: 0;
}
.list-cell {
  box-shadow: 0px 10px 13px -13px #c7d3ed;
}
.list-cell:not(:last-child)::after {
  border-bottom: 0;
}
.imageBorder {
  margin-right: 10px;
}
.content-name {
  font-size: 15px;
}
.content-des {
  color: #cbcbcb;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.pay-dialong-icon-close {
  position: absolute;
  right: 12px;
  top: 12px;
  &:hover {
    cursor: pointer;
  }
}
.pay-dialog-price {
  line-height: 80px;
  text-align: center;
  font-weight: bold;
  font-size: x-large;
  color: #e56015;
}
.pay-dialog-button-box {
  text-align: center;
  padding: 10px;
}
.pay-dialog-button {
  height: 35px;
  width: 100%;
}
.pay-container .van-cell__title {
  display: flex;
  > div {
    margin-left: 5px;
  }
}
.top_right_icon {
  position: absolute;
  top: 10px;
  right: 10px;
}
.bottom_right_icon {
  position: absolute;
  bottom: 10px;
  right: 10px;
}
.bottom_right_icon2 {
  position: absolute;
  bottom: 10px;
  right: 60px;
}
</style>
